#include "RenderGObject.h"
#include "D3D9Renderer.h"
#include "ShaderManager.h"
#include "../Animation/AnimationManager.h"

#include "../Utility/Math/MathHelper.h"

#ifdef _DEBUG
#include "../Utility/Misc/DebugOutput.h"
#endif

#include <sstream>
#include <fstream>
using std::fstream;

RenderGObject::RenderGObject() : properties(0)
{
}

RenderGObject::~RenderGObject()
{
}

void RenderGObject::LoadObject(const char* const _filePath)
{
	char line[256];
	string subPath;

	std::fstream in;
	in.open(_filePath, std::ios_base::in);

	if(in.good())
	{
		while( in.getline(line,256) )
		{
			std::istringstream newLine(line, std::istringstream::in);

			string command;

			newLine >> command;			

			if(command == "sm")
			{
				//Load static mesh
				newLine >> subPath;
				mesh.Load(subPath, mesh.STATIC_MESH);
				properties |= STATIC_MESH;
			}
			else if(command == "am")
			{
				//Load animated mesh
				newLine >> subPath;
				mesh.Load(subPath, mesh.ANIMATED_MESH);
				properties |= STATIC_MESH;
			}
			else if(command == "dt")
			{
				//Load diffuse texture
				newLine >> subPath;
				material.LoadDiffuseMap(subPath);

				properties |= DIFFUSE_MAP;
			}
			else if(command == "nt")
			{
				//Load normal texture
				newLine >> subPath;
				material.LoadNormalMap(subPath);

				properties |= NORMAL_MAP;
			}
			else if(command == "st")
			{
				//Load specular texture
				newLine >> subPath;
				material.LoadSpecularMap(subPath);

				properties |= SPECULAR_MAP;
			}
		}
	}
	else
	{
#ifdef _DEBUG
		stringstream error;
		error << "LOAD GOBJECT: " << _filePath;
		DebugOutput::Print(DebugOutput::RENDER_MSG, DebugOutput::FAILURE_CREATE, error.str().c_str());
#endif
		return;
	}

	switch(properties)
	{
	case 3:
		//Static Geometry | Diffuse Map
		Render = &RenderGObject::RenderStaticDiffuse;
		break;
	}
}

void RenderGObject::CreateBox(float _xScale, float _yScale, float _zScale)
{
	mesh.CreateBox(_xScale, _yScale, _zScale);
	material.color[0] = 1.0f; material.color[1] = 1.0f; material.color[2] = 1.0f; material.color[3] = 0.1f;
	Render = &RenderGObject::RenderStaticColor;
}

void RenderGObject::CreatePlane(float _xScale, float _yScale, float _zScale)
{
}

void RenderGObject::RenderObject()
{
	(this->*Render)();
}

void RenderGObject::RenderStaticColor()
{
	mesh.RenderIndexedPrimitive();

	ShaderManager::RenderColorIndexed(mesh,material);
}

void RenderGObject::RenderStaticDiffuse()
{
	mesh.RenderIndexedPrimitive();

	ShaderManager::RenderDiffuseIndexed(mesh,material);
}